package org.severedelays.android;

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class StatusDownloader {

  protected ArrayList<TubeLine> lines = new ArrayList<TubeLine>();
  protected String url;

  public StatusDownloader(String url) {
    this.url = url;
  }

  public ArrayList<TubeLine> getLines() {
    return lines;
  }

  public void downloadStatus() {
    HttpClient httpclient = new DefaultHttpClient();

    HttpGet httpget = new HttpGet(url);

    HttpResponse response;

    try {
      response = httpclient.execute(httpget);
      HttpEntity entity = response.getEntity();

      if (entity != null) {
        InputStream instream = entity.getContent();
        String result = convertStreamToString(instream);
        instream.close();

        JSONObject json = new JSONObject(result);
        JSONArray nameArray = json.names();
        for (int i = 0; i < nameArray.length(); i++) {
          String name = nameArray.getString(i);
          String status = json.getJSONObject(name).getString("status");
          TubeLine l = new TubeLine(name, status);
          lines.add(l);
        }
      }
    } catch (ClientProtocolException e) {
      Log.e("TubeStatus", e.toString());
    } catch (IOException e) {
      Log.e("TubeStatus", e.toString());      
    } catch (JSONException e) {
      Log.e("TubeStatus", e.toString());      
    }
  }

  private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
    } catch (IOException e) {
      Log.e("TubeStatus", e.toString());
    } finally {
      try {
        is.close();
      } catch (IOException e) {
        Log.e("TubeStatus", e.toString());
      }
    }
    return sb.toString();
  }
}
